<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>Document</title>
    <!-- 引入样式 -->
    <link rel="stylesheet" href="../../plugins/element-ui/index.css"/>
    <link rel="stylesheet" href="../../styles/common.css"/>
    <link rel="stylesheet" href="../../styles/page.css"/>
    <style>
        .addDish .el-input {
            width: 130px;
        }

        .addDish .el-input-number__increase {
            border-left: solid 1px #FFE1CA;
            background: #fff3ea;
        }

        .addDish .el-input-number__decrease {
            border-right: solid 1px #FFE1CA;
            background: #fff3ea;
        }

        .addDish input {
            border: 1px solid #ffe1ca;
        }

        .addDish .table {
            border: solid 1px #EBEEF5;
            border-radius: 3px;
        }

        .addDish .table th {
            padding: 5px 0;
        }

        .addDish .table td {
            padding: 7px 0;
        }

        .addDishList .seachDish {
            position: absolute;
            top: 10px;
            right: 20px;
        }

        .addDishList .el-dialog__body {
            padding: 0;
            border-bottom: solid 1px #ccc;
        }

        .addDishList .el-dialog__footer {
            padding-top: 27px;
        }

        .addDish {
            width: 777px;
        }

        .addDish .addBut {
            background: #ffc200;
            display: inline-block;
            padding: 0px 20px;
            border-radius: 3px;
            line-height: 40px;
            cursor: pointer;
            border-radius: 4px;
            color: #333333;
            font-weight: 500;
        }

        .addDish .content {
            background: #fafafb;
            padding: 20px;
            border: solid 1px #ccc;
            border-radius: 3px;
        }

        .addDishCon {
            padding: 0 20px;
            display: flex;
            line-height: 40px;
        }

        .addDishCon .leftCont {
            display: flex;
            border-right: solid 2px #E4E7ED;
            width: 60%;
            padding: 15px;
        }

        .addDishCon .leftCont .tabBut {
            width: 110px;
        }

        .addDishCon .leftCont .tabBut span {
            display: block;
            text-align: center;
            border-right: solid 2px #f4f4f4;
            cursor: pointer;
        }

        .addDishCon .leftCont .act {
            border-color: #FFC200 !important;
            color: #FFC200 !important;
        }

        .addDishCon .leftCont .tabList {
            flex: 1;
            padding: 15px;
        }

        .addDishCon .leftCont .tabList .table {
            border: solid 1px #f4f4f4;
            border-bottom: solid 1px #f4f4f4;
        }

        .addDishCon .leftCont .tabList .table .items {
            border-bottom: solid 1px #f4f4f4;
            padding: 0 10px;
            display: flex;
        }

        .addDishCon .leftCont .tabList .table .items .el-checkbox, .addDishCon .leftCont .tabList .table .items .el-checkbox__label {
            width: 100%;
        }

        .addDishCon .leftCont .tabList .table .items .item {
            display: flex;
            padding-right: 20px;
        }

        .addDishCon .leftCont .tabList .table .items .item span {
            display: inline-block;
            text-align: center;
            flex: 1;
        }

        .addDishCon .ritCont {
            width: 40%;
            padding: 0 15px;
        }

        .addDishCon .ritCont .item {
            box-shadow: 0px 1px 4px 3px rgba(0, 0, 0, 0.03);
            display: flex;
            text-align: center;
            padding: 0 10px;
            margin-bottom: 20px;
            border-radius: 6px;
            color: #818693;
        }

        .addDishCon .ritCont .item span:first-child {
            text-align: left;
            color: #20232A;
        }

        .addDishCon .ritCont .item .price {
            display: inline-block;
            flex: 1;
        }

        .addDishCon .ritCont .item .del {
            cursor: pointer;
        }

        .addDishCon .ritCont .item .del img {
            position: relative;
            top: 5px;
            width: 20px;
        }

        .addDishCon .el-checkbox__label {
            width: 100%;
        }

        #combo-add-app .setmealFood .el-form-item__label::before {
            content: '*';
            color: #F56C6C;
            margin-right: 4px;
        }

        #combo-add-app .uploadImg .el-form-item__label::before {
            content: '*';
            color: #F56C6C;
            margin-right: 4px;
        }
    </style>
</head>
<body>
<div class="addBrand-container" id="combo-add-app">
    <div class="container">

        <!--添加套餐表单-->
        <!--
          ref="ruleForm"：表单名称，校验的时候使用
          :model="ruleForm"：绑定表单数据对象
          :rules="rules"：绑定表单验证规则
          :inline="true": 纵向展示
          label-width="180px": label标签的宽度
        -->
        <el-form ref="ruleForm"
                 :model="ruleForm"
                 :rules="rules"
                 :inline="true"
                 label-width="180px"
                 class="demo-ruleForm">
            <div>

                <!--表单项: 套餐名称-->
                <!--
                  label="套餐名称:": 展示的文字
                  prop="name": 对应rules中的属性，若想要开启校验，则必须设置此项目
                  v-model="ruleForm.name": 双向绑定表单数据中name值
                -->
                <el-form-item label="套餐名称:" prop="name">
                    <el-input v-model="ruleForm.name" placeholder="请填写套餐名称" maxlength="20"/>
                </el-form-item>

                <!--表单项: 套餐分类-->
                <!--
                  label="套餐分类:": 展示的文字
                  prop="idType": 对应rules中的属性，若想要开启校验，则必须设置此项目
                  v-model="ruleForm.idType": 双向绑定表单数据中idType值
                  @change="$forceUpdate(): 选中值发生变化时触发
                -->
                <el-form-item label="套餐分类:" prop="idType">
                    <el-select v-model="ruleForm.idType" placeholder="请选择套餐分类" @change="$forceUpdate()">
                        <el-option v-for="(item, index) in setMealList" :key="index" :label="item.name"
                                   :value="item.id"/>
                    </el-select>
                </el-form-item>
            </div>
            <div>

                <!--表单项: 套餐价格-->
                <!--
                  label="套餐价格:": 展示的文字
                  prop="price": 对应rules中的属性，若想要开启校验，则必须设置此项目
                  v-model="ruleForm.price": 双向绑定表单数据中price值
                -->
                <el-form-item label="套餐价格:" prop="price">
                    <el-input v-model="ruleForm.price" placeholder="请设置套餐价格"/>
                </el-form-item>
            </div>
            <div>
                <!--表单项: 套餐菜品-->
                <!--
                  label="套餐菜品:": 展示的文字
                  @click="openAddDish": 点击按钮，触发openAddDish方法
                -->
                <el-form-item label="套餐菜品:" class="setmealFood">
                    <el-form-item>
                        <div class="addDish">
                            <span v-if="dishTable.length == 0" class="addBut" @click="openAddDish"> + 添加菜品</span>
                            <div v-if="dishTable.length != 0" class="content">
                                <div class="addBut" style="margin-bottom: 20px" @click="openAddDish">+ 添加菜品</div>
                                <div class="table">

                                    <!--表格控件-->
                                    <!--
                                      :data="dishTable": 绑定显示的数据
                                    -->
                                    <el-table :data="dishTable" style="width: 100%">

                                        <!--表格项: 名称-->
                                        <!--
                                          prop="name": 对应列内容的字段名，也可以使用 property 属性
                                          label="名称": 展示的文字
                                        -->
                                        <el-table-column prop="name"
                                                         label="名称"
                                                         width="180"
                                                         align="center">
                                        </el-table-column>

                                        <!--表格项: 原价-->
                                        <!--
                                          prop="price": 对应列内容的字段名，也可以使用 property 属性
                                          label="原价": 展示的文字
                                        -->
                                        <el-table-column prop="price" label="原价" width="180">
                                            <template slot-scope="scope"> {{ Number(scope.row.price) / 100 }}</template>
                                        </el-table-column>

                                        <!--表格项: 份数-->
                                        <!--
                                          prop="address": 对应列内容的字段名，也可以使用 property 属性
                                          label="份数": 展示的文字
                                        -->
                                        <el-table-column prop="address" label="份数" align="center">
                                            <template slot-scope="scope">

                                                <!--计数器控件-->
                                                <!--
                                                  v-model="scope.row.copies"：双向绑定数据中copies值
                                                  label="描述文字": 输入框关联的label文字
                                                -->
                                                <el-input-number v-model="scope.row.copies"
                                                                 size="small"
                                                                 :min="1"
                                                                 :max="99"
                                                                 label="描述文字">
                                                </el-input-number>
                                            </template>
                                        </el-table-column>

                                        <!--表格项: 操作-->
                                        <!--
                                          prop="address": 对应列内容的字段名，也可以使用 property 属性
                                          label="操作": 展示的文字
                                        -->
                                        <el-table-column prop="address" label="操作" width="180px;" align="center">
                                            <template slot-scope="scope">
                                                <el-button type="text" size="small"
                                                           @click="delDishHandle(scope.$index)"> 删除
                                                </el-button>
                                            </template>
                                        </el-table-column>
                                    </el-table>
                                </div>
                            </div>
                        </div>
                    </el-form-item>
                </el-form-item>
            </div>
            <div>
                <!--上传菜品图片-->
                <!--
                    action="/common/upload": 必选参数，上传的地址
                    :show-file-list="false": 是否显示已上传文件列表
                    :on-success="handleAvatarSuccess": 文件上传成功时调用handleAvatarSuccess方法
                    :on-change="onChange": 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会调用onChange方法
                -->
                <el-form-item label="套餐图片:" class="uploadImg">
                    <el-upload class="avatar-uploader"
                               action="/common/upload"
                               :show-file-list="false"
                               :on-success="handleAvatarSuccess"
                               :on-change="onChange"
                               ref="upload">
                        <img v-if="imageUrl" :src="imageUrl" class="avatar"></img>
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
            </div>
            <div class="address">

                <!--表单项: 套餐描述-->
                <!--
                  label="套餐描述:": 展示的文字
                  prop="region": 对应rules中的属性，若想要开启校验，则必须设置此项目
                  v-model="ruleForm.description": 双向绑定表单数据中description值
                  :rows="3": 输入框行数，只对 type="textarea" 有效
                -->
                <el-form-item label="套餐描述:">
                    <el-input v-model="ruleForm.description" type="textarea" :rows="3" placeholder="套餐描述，最长200字"
                              maxlength="200"/>
                </el-form-item>
            </div>
            <div class="subBox address">
                <el-form-item>
                    <!--取消按钮-->
                    <el-button @click="goBack()"> 取消</el-button>

                    <!--保存按钮-->
                    <el-button type="primary" @click="submitForm('ruleForm', false)"> 保存</el-button>

                    <!--保存并继续添加按钮-->
                    <el-button v-if="actionType == 'add'"
                               type="primary"
                               class="continue"
                               @click="submitForm('ruleForm', true)">
                        保存并继续添加套餐
                    </el-button>
                </el-form-item>
            </div>
        </el-form>
    </div>

    <!--对话框控件-->
    <!--
      :title="添加菜品": Dialog 的标题
      :visible.sync="dialogVisible": 是否显示 Dialog，支持 .sync 修饰符
      :before-close="handleClose": Dialog 关闭动画结束时出发 `handleClose` 方法
    -->
    <el-dialog title="添加菜品"
               class="addDishList"
               :visible.sync="dialogVisible"
               width="60%"
               :before-close="handleClose">

        <!--单行文本框控件-->
        <!--
          v-model="value"：双向绑定数据中value值
          placeholder="请输入菜品名称进行搜索"：背景提示字
          clearable: 是否可清空
          @click="seachHandle": 点击按钮，触发seachHandle方法
          @keyup.enter.native="seachHandle": 回车时，触发seachHandle方法
        -->
        <el-input v-model="value"
                  class="seachDish"
                  placeholder="请输入菜品名称进行搜索"
                  style="width: 250px"
                  size="small"
                  @keyup.enter.native="seachHandle"
                  clearable>
            <i slot="prefix" class="el-input__icon el-icon-search" style="cursor: pointer" @click="seachHandle"></i>
        </el-input>

        <div class="addDishCon">
            <div class="leftCont">
                <div v-show="seachKey.trim() == ''" class="tabBut">
                    <span v-for="(item, index) in dishType"
                          :key="index"
                          :class="{act:index == keyInd}"
                          @click="checkTypeHandle(index, item.id)">{{ item.name }}</span>
                </div>
                <div class="tabList">
                    <div class="table">
                        <div v-if="dishAddList.length == 0" style="padding-left:10px">
                            暂无菜品!
                        </div>

                        <!--多选框控件-->
                        <!--
                          v-model="checkedList"：双向绑定数据中checkedList值
                          @change="checkedListHandle": 当绑定值变化时触发checkedListHandle方法
                        -->
                        <el-checkbox-group v-if="dishAddList.length > 0"
                                           v-model="checkedList"
                                           @change="checkedListHandle">
                            <div v-for="(item, index) in dishAddList"
                                 :key="index"
                                 class="items">
                                <el-checkbox :key="index" :label="item">
                                    <div class="item">
                                        <span style="flex: 3;text-align: left">{{ item.dishName }}</span>
                                        <span>{{ item.status == 0 ? '停售' : '在售' }}</span>
                                        <span>{{ Number(item.price) / 100 }}</span>
                                    </div>
                                </el-checkbox>
                            </div>
                        </el-checkbox-group>
                    </div>
                </div>
            </div>
            <div class="ritCont">
                <div class="tit">
                    已选菜品({{ checkedList.length }})
                </div>
                <div class="items">
                    <div v-for="(item, ind) in checkedList"
                         :key="ind"
                         class="item">
                        <span>{{ item.dishName }}</span>
                        <span class="price">￥ {{ Number(item.price) / 100 }} </span>
                        <span class="del" @click="delCheck(ind)">
                            <img src="../../images/icons/btn_clean@2x.png" alt="">
                        </span>
                    </div>
                </div>
            </div>
        </div>

        <span slot="footer" class="dialog-footer">
           <!--取消按钮-->
          <el-button @click="handleClose">取 消</el-button>

            <!--确定按钮-->
          <el-button type="primary" @click="addTableList">确 定</el-button>
        </span>
    </el-dialog>
</div>
<!-- 开发环境版本，包含了有帮助的命令行警告 -->
<script src="../../plugins/vue/vue.js"></script>
<!-- 引入组件库 -->
<script src="../../plugins/element-ui/index.js"></script>
<!-- 引入axios -->
<script src="../../plugins/axios/axios.min.js"></script>
<script src="../../js/request.js"></script>
<script src="../../api/combo.js"></script>
<script src="../../js/validate.js"></script>
<script src="../../js/index.js"></script>
<script src="../../api/food.js"></script>
<script>
    new Vue({
        el: '#combo-add-app',
        data() {
            return {
                // data: 添加和修改页面的标识
                id: '',

                // data: 控制添加和修改套餐页面
                actionType: '',

                // data: 存放搜索的数据
                value: '',

                // data: 套餐分类数据列表
                setMealList: [],

                // data: 上次搜索的数据
                seachKey: '',

                // data: 菜品图片地址
                imageUrl: '',

                // data: 菜品表格数据列表
                dishTable: [],

                // data: 是否显示 Dialog
                dialogVisible: false,

                // data: 当前已选菜品数据列表(对话框外)
                checkList: [],

                // data: 套餐表单数据对象
                ruleForm: {
                    name: '',
                    categoryId: '',
                    price: '',
                    code: '',
                    image: '',
                    description: '',
                    status: true,
                    idType: '',
                },

                // data: 菜品分类列表
                dishType: [],

                // data: 当前可选菜品数据列表
                dishAddList: [],

                // data: 当前选择的菜品分类索引
                keyInd: 0,

                // data: 当前已选菜品数据列表(对话框内)
                checkedList: []
            }
        },
        computed: {
            // data: 套餐表单校验规则
            rules() {
                return {
                    name: {
                        required: true,
                        message: '请输入套餐名称',
                        trigger: 'blur',
                    },
                    idType: {
                        required: true,
                        message: '请选择套餐分类',
                        trigger: 'change',
                    },
                    price: {
                        required: true,
                        // 'message': '请输入套餐价格',
                        validator: (rules, value, callback) => {
                            if (!value) {
                                callback(new Error('请填写菜品价格'))
                            } else {
                                const reg = /^\d+(\.\d{0,2})?$/
                                if (reg.test(value)) {
                                    if (value < 10000) {
                                        callback()
                                    } else {
                                        callback(new Error('菜品价格小于10000'))
                                    }
                                } else {
                                    callback(new Error('菜品价格格式只能为数字,且最多保留两位小数'))
                                }
                            }
                        },
                        trigger: 'blur',
                    },
                }
            },
        },
        watch: {
            seachKey(value) {
                if (value.trim()) {
                    this.getDishForName(this.seachKey)
                }
            },
            checkList(value) {
                this.checkedList = value
            }
        },
        created() {
            this.getDishTypeList()
            this.getDishType()
            this.id = requestUrlParam('id')
            this.actionType = this.id ? 'edit' : 'add'
            if (this.id) {
                this.init()
            }
        },
        mounted() {
        },
        methods: {
            // method: 查询指定id的套餐
            async init() {
                querySetmealById(this.id).then((res) => {
                    if (String(res.code) === '1') {
                        this.ruleForm = res.data
                        this.ruleForm.status = res.data.status === '1'
                        this.ruleForm.price = res.data.price / 100
                        this.imageUrl = `/common/download?name=${res.data.image}`
                        this.checkList = res.data.setmealDishes
                        this.dishTable = res.data.setmealDishes
                        this.ruleForm.idType = res.data.categoryId
                        console.log("this.checkList")
                        console.log(this.checkList)
                    } else {
                        this.$message.error(res.msg || '操作失败')
                    }
                })
            },

            // method: 保存搜索词(对话框内)
            seachHandle() {
                this.seachKey = this.value
            },

            // method: 获取套餐分类列表(对话框外)
            getDishTypeList() {
                getCategoryList({type: 2}).then((res) => {
                    if (res.code === 1) {
                        this.setMealList = res.data.map((obj) => ({...obj, idType: obj.id}))
                    } else {
                        this.$message.error(res.msg || '操作失败')
                    }
                })
            },

            // method: 删除套餐菜品(对话框外)
            delDishHandle(index) {
                this.dishTable.splice(index, 1)
                this.checkList.splice(index, 1)
            },

            // 获取添加菜品数据
            getCheckList(value) {
                this.checkList = [...value]
            },

            // method: 添加菜品(对话框外)
            openAddDish() {
                this.seachKey = ''
                this.dialogVisible = true
                //搜索条件清空，菜品重新查询，菜品类别选第一个重新查询
                this.value = ''
                this.keyInd = 0
                this.getDishList(this.dishType[0].id)
            },

            // method: 取消添加菜品(对话框内)
            handleClose(done) {
                this.dialogVisible = false
            },

            // method: 保存添加菜品列表(对话框内)
            addTableList() {
                this.dishTable = JSON.parse(JSON.stringify(this.checkList))
                this.dishTable.forEach((n) => {
                    n.copies = 1
                })
                this.dialogVisible = false
                // 添加处理逻辑清空选中list
                this.checkList = []
            },

            // method: 提交表单(对话框外)
            submitForm(formName, st) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        let prams = {...this.ruleForm}
                        prams.price *= 100
                        prams.setmealDishes = this.dishTable.map((obj) => ({
                            copies: obj.copies,
                            dishId: obj.dishId,
                            name: obj.name,
                            price: obj.price,
                        }))
                        prams.status = this.ruleForm ? 1 : 0
                        prams.categoryId = this.ruleForm.idType
                        if (prams.setmealDishes.length < 1) {
                            this.$message.error('请选择菜品！')
                            return
                        }
                        if (!this.imageUrl) {
                            this.$message.error('请上传套餐图片')
                            return
                        }
                        // delete prams.dishList
                        if (this.actionType == 'add') {
                            delete prams.id
                            addSetmeal(prams)
                                .then((res) => {
                                    if (res.code === 1) {
                                        this.$message.success('套餐添加成功！')
                                        if (!st) {
                                            this.goBack()
                                        } else {
                                            this.$refs.ruleForm.resetFields()
                                            this.dishTable = []
                                            this.ruleForm = {
                                                name: '',
                                                categoryId: '',
                                                price: '',
                                                code: '',
                                                image: '',
                                                description: '',
                                                status: true,
                                                id: '',
                                                idType: '',
                                            }
                                            this.imageUrl = ''
                                        }
                                    } else {
                                        this.$message.error(res.msg || '操作失败')
                                    }
                                })
                                .catch((err) => {
                                    this.$message.error('请求出错了：' + err)
                                })
                        } else {
                            delete prams.updateTime
                            editSetmeal(prams)
                                .then((res) => {
                                    if (res.code === 1) {
                                        this.$message.success('套餐修改成功！')
                                        this.goBack()
                                    } else {
                                        this.$message.error(res.msg || '操作失败')
                                    }
                                })
                                .catch((err) => {
                                    this.$message.error('请求出错了：' + err)
                                })
                        }
                    } else {
                        return false
                    }
                })
            },

            // method: 文件上传成功时调用handleAvatarSuccess方法
            handleAvatarSuccess(response, file, fileList) {
                // this.imageUrl = response.data
                if (response.code === 0 && response.msg === '未登录') {
                    window.top.location.href = '/backend/page/login/login.html'
                } else {
                    this.imageUrl = `/common/download?name=${response.data}`
                    this.ruleForm.image = response.data
                }
            },

            // method: 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会调用onChange方法
            onChange(file) {
                if (file) {
                    const suffix = file.name.split('.')[1]
                    const size = file.size / 1024 / 1024 < 2
                    if (['png', 'jpeg', 'jpg'].indexOf(suffix) < 0) {
                        this.$message.error('上传图片只支持 png、jpeg、jpg 格式！')
                        this.$refs.upload.clearFiles()
                        return false
                    }
                    if (!size) {
                        this.$message.error('上传文件大小不能超过 2MB!')
                        return false
                    }
                    return file
                }
            },

            // method: 调用父窗口的发送请求方法(对话框外)
            goBack() {
                window.parent.menuHandle(
                    {
                        id: '5',
                        url: '/backend/page/combo/list.html',
                        name: '套餐管理',
                    },
                    false
                )
            },

            // method: 获取菜品分类(对话框内)
            getDishType() {
                getCategoryList({'type': 1}).then(res => {
                    if (res.code === 1) {
                        this.dishType = res.data
                        this.getDishList(res.data[0].id)
                    } else {
                        this.$message.error(res.msg)
                    }
                })
            },

            // method: 通过菜品分类ID获取菜品列表分类(对话框内)
            getDishList(id) {
                queryDishList({categoryId: id}).then(res => {
                    if (res.code === 1) {
                        if (res.data.length == 0) {
                            this.dishAddList = []
                            return
                        }
                        let newArr = res.data;
                        newArr.forEach((n) => {
                            n.dishId = n.id
                            n.copies = 1
                            // n.dishCopies = 1
                            n.dishName = n.name
                        })
                        this.dishAddList = newArr
                    } else {
                        this.$message.error(res.msg)
                    }
                })
            },

            // method: 关键词搜索菜品列表分类(对话框内)
            getDishForName(name) {
                queryDishList({name}).then(res => {
                    if (res.code === 1) {
                        let newArr = res.data
                        newArr.forEach((n) => {
                            n.dishId = n.id
                            n.dishName = n.name
                        })
                        this.dishAddList = newArr
                    } else {
                        this.$message.error(res.msg)
                    }
                })
            },

            // method: 切换菜品分类数据(对话框内)
            checkTypeHandle(ind, id) {
                this.keyInd = ind
                this.getDishList(id)
            },

            // method: 同步对话框外的菜品数据列表
            checkedListHandle(value) {
                this.getCheckList(this.checkedList)
            },

            // method: 删除已选菜品(对话框内)
            delCheck(ind) {
                this.checkedList.splice(ind, 1)
            }
        },
    })
</script>
</body>
</html>
